package com.shaonianyou.component;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

/**
 * 权限认证异常跳转控制
 * 
 * @author Empty
 *
 */
public class RestAuthenticationEntryPoint extends
		LoginUrlAuthenticationEntryPoint {

	public RestAuthenticationEntryPoint(String loginFormUrl) {
		super(loginFormUrl);
	}

	@Override
	public void commence(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authException)
			throws IOException, ServletException {
		String header = request.getHeader("X-Requested-With");
		// session过期  请求返回401
		if (StringUtils.isNotEmpty(header) && header.equals("XMLHttpRequest")) {
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
					"Unauthorized");
		} else {
			super.commence(request, response, authException);// 登录登录页面
		}
	}
}
